<template>
    <Page class="container_page" :use-header="true" title="聊天室">
        <a-card>
            <a-button type="primary" v-if="online" @click="handleOffline">下线</a-button>
            <a-button type="primary" v-else @click="handleOnline">上线</a-button>
        </a-card>
    </Page>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import store from '@/store';
// Api
import { ApiWebScoket } from '@/axios/api';
// Component
import Page from '@/component/layout/Page.vue';
// Model
import { Result } from '@/model/common';
// Util
import { WebSocketUtil } from '@/util';

const online = ref<boolean>(WebSocketUtil.isConnected());
const chatId = ref<string>(store.state.chatId);

onMounted(() => {
    init();
});

const init = () => {
    if (!chatId.value) {
        ApiWebScoket.getChatId().then((res: Result) => {
            chatId.value = res.data;
            store.commit('chatId', chatId.value);
        });
    }
};

const handleOnline = () => {
    WebSocketUtil.connect(
        { id: chatId.value, token: store.state.token },
        () => {
            online.value = true;
        },
        () => {
            online.value = false;
        }
    );
};

const handleOffline = () => {
    WebSocketUtil.disconnect(() => {
        online.value = false;
    });
};
</script>

<style lang="less" scoped></style>
